import $C from '@/common/config.js';
import { local } from '@/common/local.js';
export default {
	common:{
		method: 'GET',
		data: {}
	},
	request(options = {}){
		const token = local.get("token") || ''
		options.url = $C.webUrl + options.url
		options.method = options.method || this.common.method
		options.header = Object.assign({
			"content-type": "application/json",
			"Authorization": 'Bearer ' + token
		}, options.other ? options.other : {})
		return new Promise((res,rej)=>{
			if (options.loading) {
				uni.showLoading({
					mask: true
				})
			}
			uni.request({
				...options,
				success: (result) => {
					if (options.loading) {
						uni.hideLoading()
					}
					// 返回原始数据
					if(options.native){
						return res(result)
					}
					// console.log('--result---', result)
					// 请求服务端失败
					if (result.statusCode != 200 && !options.notoast) {
						if (result.statusCode == 401) {
							return
						} else if (token) {
							
						}
						return res(result.data)
					}
					if (result.statusCode == 200) {
						res(result.data)
					}
				},
				fail:(error)=>{
					if (options.loading) {
						uni.hideLoading()
					}
					uni.showToast({
						title: error.errMsg || '请求失败',
						icon: 'none'
					});
					return rej()
				}
			});
		})
	},
	get(url, data = {},options = {}){
		options.url = url
		options.data = data
		options.method = 'GET'
		return this.request(options)
	},
	post(url,data = {},options = {}){
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	}
}